<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>年度运营指标</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div style="margin: 24px;">
      <a-card  :bordered="false">
        <a-form layout="inline">
          <a-form-item label="选择年度">
            <a-date-picker mode="year" :value="year" :allowClear="false" format="YYYY" :open="isopen" @openChange="onOpenChange" @panelChange="onPanelChange"></a-date-picker>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="handleSubmit">查询</a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="configTarget">年度运营指标配置</a-button>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <a-row>
      <a-col v-if="hasZhiBiao" :span="24">
        <div style="margin: 24px;">
          <a-card :bordered="false">
            <p v-if="data1.length > 0" style=" height: 30px" ><a-button type="primary" style="float:right; margin-bottom: 10px;" @click="exportExcel1">导出Excel</a-button></p>
            <a-table :loading="loading" :columns="getColumns('年度')" :dataSource="data1" :pagination="false" rowKey="time"></a-table>
          </a-card>
        </div>
        <div style="margin: 24px;">
          <a-card  :bordered="false">
            <p v-if="data2.length > 0" style=" height: 30px" ><a-button type="primary" style="float:right; margin-bottom: 10px;" @click="exportExcel2">导出Excel</a-button></p>
            <a-table :loading="loading" :columns="getColumns('季度')" :dataSource="data2" :pagination="false" rowKey="time"></a-table>
          </a-card>
        </div>
        <div style="margin: 24px;">
          <a-card  :bordered="false">
            <p v-if="data3.length > 0" style=" height: 30px" ><a-button type="primary" style="float:right; margin-bottom: 10px;" @click="exportExcel3">导出Excel</a-button></p>
            <a-table :loading="loading" :columns="getColumns('月度')" :dataSource="data3" :pagination="false" rowKey="time"></a-table>
            </a-card>
        </div>
      </a-col>
      <a-col v-if="!hasZhiBiao" :span="24">
        <div style="margin: 0 24px;">
          <a-card :bordered="false"><a-empty :description="`${year.format('YYYY')}年度运营指标未配置`"/></a-card>
        </div>
      </a-col>
    </a-row>

    <!-- 运营指标记录 -->
    <a-modal :visible="visible" title="运营指标记录" :footer="null" width="800px"
      centered destoryOnClose :maskClosable="false"
      @cancel="handleCancel"
    >
      <p><a-button type="primary" @click="addItem">添加指标</a-button></p>
      <a-table :columns="columnsModal" :dataSource="dataModal" :pagination="false" rowKey="year">
        <template slot="time" slot-scope="text">
          <a-date-picker v-if="!text" mode="year" :value="yearModal" :allowClear="false" format="YYYY" :open="isopenModal" @openChange="onOpenChangeModal" @panelChange="onPanelChangeModal"></a-date-picker>
          <span v-if="text">{{text}}</span>
        </template>
        <template slot="target" slot-scope="text">
          <a-input-number v-if="!text" :min="0" :precision="2" :max="999999999999.99" v-model="targetYearModal" @blur="previewData"></a-input-number>
          <span v-if="text">{{text}}</span>
        </template>
        <template slot="opt" slot-scope="text, record">
          <a v-if="isEditYear(record.year)" @click="editConfig(record.targetId)">编辑</a>
          <a v-if="!isEditYear(record.year) && record.year !== 0" @click="viewConfig(record.targetId)">查看</a>
          <a v-if="record.year === 0" @click="addOneTarget">保存</a>
        </template>
      </a-table>

      <!-- 运营指标配置 -->
      <a-modal :visible="visible2" :title="titleConfig" width="720px"
        centered destoryOnClose :maskClosable="false"
        okText="保存"
        @ok="handleOk"
        @cancel="handleCancel2"
      >
        <a-row>
          <a-col :span="24">
            <p>年度指标金额(元)：{{form.targetYear}}</p>
            <a-table :columns="columnsModalConfig" :dataSource="dataModalConfig" :pagination="false" rowKey="text">
              <template slot="target" slot-scope="text, record, index">
                <span v-if="!record.isData || !editabled">{{text}}</span>
                <a-input-number v-if="record.isData && editabled" :min="0" :precision="2" :max="999999999999.99" v-model="dataModalConfig[index].value" @change="onChangeData"></a-input-number>
              </template>
              <template slot="target2" slot-scope="text, record, index">
                <span v-if="!record.isData || !editabled">{{text}}</span>
                <a-input-number v-if="record.isData && editabled" :min="0" :precision="2" :max="999999999999.99" v-model="dataModalConfig[index].value2" @change="onChangeData"></a-input-number>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-modal>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import {commonExport} from '@/api/request'
import {queryTargetJiateByYear, queryTargetJiateList, addTargetJiate, queryTargetJiateDetail} from '@/api/dataBI'
export default {
  data () {
    const columnsModal = [
      {
        title: '年度',
        dataIndex: 'year',
        width: '100px',
        scopedSlots: {customRender: 'time'}
      },
      {
        title: '年度指标（元）',
        dataIndex: 'targetYear',
        scopedSlots: {customRender: 'target'}
      },
      {
        title: '第一季度指标(元)',
        dataIndex: 'targetQuarter1'
      },
      {
        title: '第二季度指标(元)',
        dataIndex: 'targetQuarter2'
      },
      {
        title: '第三季度指标(元)',
        dataIndex: 'targetQuarter3'
      },
      {
        title: '第四季度指标(元)',
        dataIndex: 'targetQuarter4'
      },
      {
        width: '100px',
        scopedSlots: {customRender: 'opt'}
      }
    ]

    const columnsModalConfig = [
      {
        title: '时间',
        dataIndex: 'text'
      },
      {
        title: '指标金额(元)',
        dataIndex: 'value',
        scopedSlots: {customRender: 'target'}
      },
      {
        title: '时间',
        dataIndex: 'text2'
      },
      {
        title: '指标金额(元)',
        dataIndex: 'value2',
        scopedSlots: {customRender: 'target2'}
      }
    ]

    return {
      isopen: false,
      year: null,
      isopenModal: false,
      yearModal: null,
      targetYearModal: '',
      data: {},
      loading: false,
      data1: [],
      data2: [],
      data3: [],
      // modal
      visible: false,
      columnsModal,
      dataModal: [],
      // 配置
      titleConfig: '',
      visible2: false,
      columnsModalConfig,
      dataModalConfig: [],
      editabled: false,
      form: {
        targetId: null,
        targetYear: ''
      },
      hasZhiBiao: true,
      hasSelectedYears: [] // 已选择的年度
    }
  },
  methods: {
    // 年份
    onOpenChange (status) {
      this.isopen = status
    },
    onPanelChange (v) {
      this.year = v
      this.isopen = false
    },
    // 年份 modal
    onOpenChangeModal (status) {
      this.isopenModal = status
    },
    onPanelChangeModal (v) {
      if (moment().startOf('year') > v) {
        this.$message.error('不可选今年以及之前的年份')
        return false
      } else if (this.hasSelectedYears.includes(v.format('YYYY'))) {
        this.$message.error('该年份运营指标已配置')
        return false
      }
      this.yearModal = v
      this.isopenModal = false
    },
    getColumns (text) {
      return [
        {
          title: '序号',
          width: 80,
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '时间',
          dataIndex: 'time'
        },
        {
          title: `${text}指标(元)`,
          dataIndex: 'target'
        },
        {
          title: '完成指标（元）',
          dataIndex: 'targetComplete'
        },
        {
          title: '剩余指标（元）',
          dataIndex: 'targetRemain'
        },
        {
          title: `${text}完成比`,
          dataIndex: 'targetRateStr'
        }
      ]
    },
    dealTargetDatas () {
      this.data1 = [
        {
          time: `${this.year.format('YYYY')}年`,
          target: this.data.targetYear.toFixed(2),
          targetComplete: this.data.targetYearComplete.toFixed(2),
          targetRemain: this.data.targetYearRemain.toFixed(2),
          targetRateStr: this.data.targetYearRate.toFixed(2) + '%'
        }
      ]

      this.data2 = ['一', '二', '三', '四'].map((v, i) => {
        return {
          time: `第${v}季度`,
          target: this.data[`targetQuarter${i + 1}`].toFixed(2),
          targetComplete: (this.data[`targetQuarter${i + 1}Complete`]).toFixed(2),
          targetRemain: (this.data[`targetQuarter${i + 1}Remain`]).toFixed(2),
          targetRateStr: (this.data[`targetQuarter${i + 1}Rate`]).toFixed(2) + '%'
        }
      })

      this.data3 = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'].map((v, i) => {
        return {
          time: `${v}月`,
          target: this.data[`targetMonth${i + 1}`].toFixed(2),
          targetComplete: (this.data[`targetMonth${i + 1}Complete`]).toFixed(2),
          targetRemain: this.data[`targetMonth${i + 1}Remain`].toFixed(2),
          targetRateStr: this.data[`targetMonth${i + 1}Rate`].toFixed(2) + '%'
        }
      })
    },
    handleSubmit () {
      this.loading = true
      queryTargetJiateByYear({year: this.year.format('YYYY')}).then(rsp => {
        this.data = rsp.data
        if (rsp.data && rsp.data.id) {
          this.dealTargetDatas()
          this.hasZhiBiao = true
        } else {
          this.hasZhiBiao = false
          this.data1 = []
          this.data2 = []
          this.data3 = []
        }
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    // 初始化运营指标配置
    initTargetYearList () {
      queryTargetJiateList({}).then(rsp => {
        this.dataModal = rsp.data.map(v => {
          for (let i in v) {
            if (i !== 'targetId' && i !== 'year' && v[i]) {
              v[i] = v[i].toFixed(2)
            }
          }
          return v
        })

        let hasSelectedYears = []
        rsp.data.forEach(v => {
          hasSelectedYears.push(v.year)
        })
        this.hasSelectedYears = hasSelectedYears
      })
    },
    addItem () {
      if (!this.$root._bc.create) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.dataModal.length === 0 || (this.dataModal.length > 0 && this.dataModal[0].year !== 0)) {
        let t = [...this.dataModal]
        t.unshift({year: 0})
        this.dataModal = t
      }
    },
    isEditYear (year) {
      return moment().startOf('year').format('YYYY') <= year
    },
    configTarget () {
      if (!this.$root._bc.set) {
        this.$message.error('您无此权限！')
        return
      }
      this.initTargetYearList()
      this.yearModal = null
      this.targetYearModal = ''
      this.visible = true
    },
    addOneTarget () {
      if (!this.yearModal || !this.targetYearModal) {
        this.$message.error('请填写完整数据')
        return false
      }
      addTargetJiate({
        year: this.yearModal.format('YYYY'),
        targetYear: this.targetYearModal
      }).then(rsp => {
        this.$message.success('更新成功')
        this.initTargetYearList()
      })
    },
    handleCancel () {
      this.visible = false
    },
    // 配置
    initConfig (targetId) {
      this.form.targetId = targetId
      queryTargetJiateDetail({targetId}).then(rsp => {
        const t = rsp.data
        this.form.targetYear = t.targetYear.toFixed(2)
        this.dataModalConfig = [
          {
            text: '第一季度',
            text2: '第二季度',
            value: t.targetQuarter1.toFixed(2),
            value2: t.targetQuarter2.toFixed(2)
          },
          {
            text: '01月',
            text2: '04月',
            value: t.targetMonth1.toFixed(2),
            value2: t.targetMonth4.toFixed(2),
            isData: true
          },
          {
            text: '02月',
            text2: '05月',
            value: t.targetMonth2.toFixed(2),
            value2: t.targetMonth5.toFixed(2),
            isData: true
          },
          {
            text: '03月',
            text2: '06月',
            value: t.targetMonth3.toFixed(2),
            value2: t.targetMonth6.toFixed(2),
            isData: true
          },
          {
            text: '第三季度',
            text2: '第四季度',
            value: t.targetQuarter3.toFixed(2),
            value2: t.targetQuarter4.toFixed(2)
          },
          {
            text: '07月',
            text2: '10月',
            value: t.targetMonth7.toFixed(2),
            value2: t.targetMonth10.toFixed(2),
            isData: true
          },
          {
            text: '08月',
            text2: '11月',
            value: t.targetMonth8.toFixed(2),
            value2: t.targetMonth11.toFixed(2),
            isData: true
          },
          {
            text: '09月',
            text2: '12月',
            value: t.targetMonth9.toFixed(2),
            value2: t.targetMonth12.toFixed(2),
            isData: true
          }
        ]
      })
    },
    viewConfig (id) {
      this.editabled = false
      this.initConfig(id)
      this.titleConfig = '查看运营指标配置'
      this.visible2 = true
    },
    editConfig (id) {
      if (!this.$root._bc.edit) {
        this.$message.error('您无此权限！')
        return
      }
      this.editabled = true
      this.initConfig(id)
      this.titleConfig = '编辑运营指标配置'
      this.visible2 = true
    },
    exportExcel1 () {
      commonExport('/truckReport/exportTargetJiateByYear', {
        year: this.year.format('YYYY'),
        type: 1,
        columns: this.getColumns('年度')
      })
    },
    exportExcel2 () {
      commonExport('/truckReport/exportTargetJiateByYear', {
        year: this.year.format('YYYY'),
        type: 2,
        columns: this.getColumns('季度')
      })
    },
    exportExcel3 () {
      commonExport('/truckReport/exportTargetJiateByYear', {
        year: this.year.format('YYYY'),
        type: 3,
        columns: this.getColumns('月度')
      })
    },
    onChangeData () { // 动态数据
      this.dataModalConfig[0].value = (parseFloat(this.dataModalConfig[1].value) + parseFloat(this.dataModalConfig[2].value) + parseFloat(this.dataModalConfig[3].value)).toFixed(2)
      this.dataModalConfig[0].value2 = (parseFloat(this.dataModalConfig[1].value2) + parseFloat(this.dataModalConfig[2].value2) + parseFloat(this.dataModalConfig[3].value2)).toFixed(2)
      this.dataModalConfig[4].value = (parseFloat(this.dataModalConfig[5].value) + parseFloat(this.dataModalConfig[6].value) + parseFloat(this.dataModalConfig[7].value)).toFixed(2)
      this.dataModalConfig[4].value2 = (parseFloat(this.dataModalConfig[5].value2) + parseFloat(this.dataModalConfig[6].value2) + parseFloat(this.dataModalConfig[7].value2)).toFixed(2)
      this.form.targetYear = (parseFloat(this.dataModalConfig[0].value) + parseFloat(this.dataModalConfig[0].value2) + parseFloat(this.dataModalConfig[4].value) + parseFloat(this.dataModalConfig[4].value2)).toFixed(2)
    },
    handleOk () {
      addTargetJiate({
        ...this.form,
        targetQuarter1: this.dataModalConfig[0].value, // 第一季度指标
        targetQuarter2: this.dataModalConfig[0].value2, // 第二季度指标
        targetQuarter3: this.dataModalConfig[4].value, // 第三季度指标
        targetQuarter4: this.dataModalConfig[4].value2, // 第四季度指标
        targetMonth1: this.dataModalConfig[1].value, // 1月指标
        targetMonth2: this.dataModalConfig[2].value, // 2月指标
        targetMonth3: this.dataModalConfig[3].value, // 3月指标
        targetMonth4: this.dataModalConfig[1].value2, // 4月指标
        targetMonth5: this.dataModalConfig[2].value2, // 5月指标
        targetMonth6: this.dataModalConfig[3].value2, // 6月指标
        targetMonth7: this.dataModalConfig[5].value, // 7月指标
        targetMonth8: this.dataModalConfig[6].value, // 8月指标
        targetMonth9: this.dataModalConfig[7].value, // 9月指标
        targetMonth10: this.dataModalConfig[5].value2, // 10月指标
        targetMonth11: this.dataModalConfig[6].value2, // 11月指标
        targetMonth12: this.dataModalConfig[7].value2 // 12月指标
      }).then(rsp => {
        this.$message.success('添加成功')
        this.visible2 = false
        this.initTargetYearList()
      })
    },
    handleCancel2 () {
      this.visible2 = false
    },
    previewData () {
      if (this.targetYearModal) {
        this.dataModal[0].targetQuarter1 = this.dataModal[0].targetQuarter2 = this.dataModal[0].targetQuarter3 = this.dataModal[0].targetQuarter4 = parseInt(parseFloat(this.targetYearModal / 4) * 100) / 100
      } else {
        this.dataModal[0].targetQuarter1 = this.dataModal[0].targetQuarter2 = this.dataModal[0].targetQuarter3 = this.dataModal[0].targetQuarter4 = 0
      }
      this.dataModal = [...this.dataModal]
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.year = moment().startOf('year')
      this.handleSubmit()
    })
  }
}
</script>

<style lang="less" scoped>

</style>
